package cn.lhx.blog.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.lhx.blog.dao.DaoArticle;
import cn.lhx.blog.pojo.Archive;
import cn.lhx.blog.pojo.Article;
import cn.lhx.blog.service.ArticleService;

/**
 * 日志Service对象
 * 
 * @author lhx
 * 
 */
@Transactional
public class ArticleServiceBean implements ArticleService {
	@Resource(name = "daoArticle")
	private DaoArticle daoArticle;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.lhx.blog.service.bean.ArticleService#saveArticle(cn.lhx.blog.pojo.
	 * Article)
	 */
	public Article saveArticle(Article article) {
		daoArticle.insert(article);
		return article;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.lhx.blog.service.bean.ArticleService#delArticle(cn.lhx.blog.pojo.Article
	 * )
	 */
	public void delArticle(Serializable id) {
		daoArticle.delete((Integer)id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.lhx.blog.service.bean.ArticleService#modifyArticle(cn.lhx.blog.pojo
	 * .Article)
	 */
	public Article UpdateArticle(Article article) {
		daoArticle.update(article);
		return article;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Article getArtilceById(Serializable id) {
		Article article = null;
		article = (Article) daoArticle.getById((Integer)id);
		return article;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public List<Article> getArticles(Serializable _begin, Serializable _size) {
		List<Article> articles = new ArrayList<Article>();
		articles = (List<Article>) daoArticle.getList((Integer)_begin,(Integer) _size);
		return articles;
	}
	
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public long statsArticleCount() {
		long count=(Long)(daoArticle.executeQuery("select count(a.id) from Article a").get(0));
		return count;
	}

	public List<Archive> getArchives() {
		List<Archive> archives =new ArrayList<Archive>();
		String sql=" select id as {ac.id},postTime as {ac.log_year_month},count(*)as {ac.count} from tb_article ac group by  DATE_FORMAT(postTime,'%Y-%m');";
		org.hibernate.SQLQuery sqlQuery = daoArticle.getSessionFactory().getCurrentSession().createSQLQuery(sql);
		sqlQuery.addEntity("ac",Archive.class);
		archives=sqlQuery.list();
		for(int i=0;i<archives.size();i++){
			System.err.println(archives.get(i).getLog_year_month().toString());
		}
		return archives;
	}



}
